import requests
from .yamlwrite import WriterYaml
from common.recordlog import logs


class SendRequest(object):

    def __init__(self):
        pass

    def run_main(self, url, method, data=None, header=None, **kwargs):
        """
        发送HTTP请求并获取响应结果
        
        Args:
            url (str): 请求的URL地址
            method (str): 请求的HTTP方法，如GET、POST等
            data (dict, optional): 请求的参数，如果是GET请求，则作为查询参数；如果是POST请求，则作为请求体。默认为None。
            header (dict, optional): 请求的HTTP头信息。默认为None。
            **kwargs: 其他可选参数，如超时时间等。
        
        Returns:
            requests.Response: 请求的响应结果对象，包含状态码、响应内容等信息。
        
        Raises:
            HTTPError: 当HTTP请求返回的状态码表示错误时，抛出此异常。
            ConnectionError: 当连接请求URL时发生错误时，抛出此异常。
            Timeout: 当请求超时时，抛出此异常。
            RequestException: 当发生其他请求异常时，抛出此异常。
        """
        try:
            cookie = {}
            method = method.lower()
            logs.info(f"请求方式是:{method}")
            logs.info(f"请求地址是:{url}")
            logs.info(f"请求参数是{data}")
            logs.info(f'请求头是{header}')
            if method == 'get':
                response = requests.request(method=method, url=url, params=data, headers=header, **kwargs)
            elif method == 'post':
                if header and "application/json" in header.get("Content-Type", ""):
                    response = requests.request(method=method, url=url, json=data, headers=header, **kwargs)
                else:
                    response = requests.request(method=method, url=url, data=data, headers=header, **kwargs)
            else:
                response = requests.request(method=method, url=url, data=data, headers=header, **kwargs)

            if response.cookies:
                set_cookie = requests.utils.dict_from_cookiejar(response.cookies)
                cookie['Cookie'] = set_cookie['access_token_cookie']
                WriterYaml().write({'Cookie': set_cookie['access_token_cookie']})

            # 检查响应状态码
            response.raise_for_status()
            response.encoding = 'utf8'
            return response

        except requests.exceptions.HTTPError as http_err:
            # 处理 HTTP 请求异常
            print("HTTP error occurred:", http_err)
        except requests.exceptions.ConnectionError as conn_err:
            # 处理连接异常
            print("Connection error occurred:", conn_err)
        except requests.exceptions.Timeout as timeout_err:
            # 处理超时异常
            print("Timeout error occurred:", timeout_err)
        except requests.exceptions.RequestException as req_err:
            # 处理其他请求异常
            print("Request Exception occurred:", req_err)
        except Exception as e:
            # 处理其他异常
            print("An error occurred:", e)

        return None
